package com.xzy.rabbit.demo.workqueue.c;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 工作模式（Work Queue）
 *
 * @author xzy
 * @date 2021年9月23日
 */
@Slf4j
@Data
class Consumer implements Runnable {

    /**
     * TCP连接
     */
    private final Connection connection;
    /**
     * 队列名称
     */
    private final String queueName;
    /**
     * 线程同步（实现多个工作线程的同步）
     */
    private final CountDownLatch countDownLatch;
    /**
     * 执行时间（模拟工作线程处理每个任务的时间）
     */
    private final long workTime;
    /**
     * 是否模拟工作中出现异常的情况
     */
    private final boolean haveError;

    public Consumer(Connection connection, String queueName, CountDownLatch countDownLatch, long workTime, boolean haveError) {
        this.connection = connection;
        this.queueName = queueName;
        this.countDownLatch = countDownLatch;
        this.workTime = workTime;
        this.haveError = haveError;
    }

    private boolean closed = false;

    /**
     * 消费消息
     */
    public void consume() throws IOException {

        // 1.获取信道
        Channel channel = connection.createChannel();

        // 2.接收消息（消费）_手动应答
        String currentThread = Thread.currentThread().getName();
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            try {

                // 模拟异常
                if (this.closed) {
                    return;
                }

                // 1.处理消息
                log.info(currentThread + " 成功接收：{}\n", new String(message.getBody()));
                Thread.sleep(workTime);

                // 模拟异常
                if (haveError && Math.random() < 0.5) {
                    log.info(currentThread + " 出现异常!!!：{}\n", new String(message.getBody()));
                    channel.close();
                    this.closed = true;
                }

                // 2.手动应答
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);

                log.info(currentThread + " 确认接收：{}\n", new String(message.getBody()));
                countDownLatch.countDown();

            } catch (Exception e) {
                // e.printStackTrace();
            }
        };

        CancelCallback cancelCallback = consumerTag -> {
            log.info(currentThread + " 取消接收");
        };

        channel.basicConsume(queueName, false, deliverCallback, cancelCallback);
    }

    @Override
    public void run() {
        try {
            consume();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
